<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of FilterwordComtroller
 *
 * @author tuancasi
 */
class FilterwordController extends Controller {
    /*
     * show list filter word
     */

    public function actionIndex() {

	$model = new FilterWord('search');
	$model->unsetAttributes();  // clear any default values

	if (isset($_GET['FilterWord'])) {
	    $model->attributes = $_GET['FilterWord'];
	}
	$this->render('index', array(
	    'model' => $model
	));
    }

    /**
     * add filter word 
     */
    public function actionCreate() {
	$model = new FilterWord;

	if (isset($_POST['submit'])) {
	    $model->attributes = $_POST['FilterWord'];
	    if ($model->validate()) {
		$model->user_id = user()->id;
		if ($model->save()) {
		    $this->_clearCache('aFilterWord');
		    $this->redirect('index');
		}
	    }
	}
	$this->render('create', array('model' => $model));
    }

    /**
     * update filter
     */
    public function actionUpdate($id) {
	$model = FilterWord::model()->findByPk($id);
	if (isset($_POST['submit'])) {
	    $model->attributes = $_POST['FilterWord'];
	    if ($model->validate()) {
		$model->user_id = user()->id;
		if ($model->save()) {
		    $this->_clearCache('aFilterWord');
		    $this->redirect('index');
		}
	    }
	}
	$this->render('update', array('model' => $model));
    }

    /*
     * delete filter
     */

    public function actionDelete($id) {
	$model = FilterWord::model()->findByPk($id);
	if ($model) {
	    $this->_clearCache('aFilterWord');
	    $model->delete();
	}
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
	if (isset($_POST['ajax']) && $_POST['ajax'] === 'filter-word-form') {
	    echo CActiveForm::validate($model);
	    Yii::app()->end();
	}
    }

    /*
     * clear cache on front end
     */

    private function _clearCache($key) {
	//Send Post Request to Frontend
	$timeout = 30;
	$curl = curl_init();
	$pvars = array('key' => $key);
	curl_setopt($curl, CURLOPT_URL, FRONT_SITE_URL . 'site/caching');
	curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
	curl_setopt($curl, CURLOPT_POST, 1);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
	$result = curl_exec($curl);
	curl_close($curl);

	return $result == '0' ? false : true;
	break;
    }

}

